"""
完全干净的Flask应用启动文件
避免所有模型冲突问题
"""

import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from flask import Flask, render_template, redirect, url_for, request, flash, session
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, EqualTo, Email, Length
from sqlalchemy import text

# 创建全新的应用实例
app = Flask(__name__)

# 直接配置数据库连接（避免使用config.py中的冲突配置）
app.config['SECRET_KEY'] = 'your-very-secure-secret-key-here-12345'
app.config['SESSION_COOKIE_SECURE'] = False  # 开发环境设为False
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
app.config['PERMANENT_SESSION_LIFETIME'] = 600  # 会话永久生存时间10分钟
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:1026@localhost/house_info'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# 创建新的数据库实例
db = SQLAlchemy(app)

# 定义与实际数据库匹配的用户模型
class UserActual(db.Model):
    """用户表 - 与实际数据库结构匹配"""
    __tablename__ = 'user_info'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100))  # 实际数据库字段名为name
    password = db.Column(db.String(100))
    email = db.Column(db.String(100))
    addr = db.Column(db.String(100))
    collect_id = db.Column(db.String(250))
    seen_id = db.Column(db.String(250))

    def __repr__(self):
        return f'<UserActual {self.name}>'

# 定义登录表单
class LoginForm(FlaskForm):
    username = StringField('用户名', validators=[DataRequired()])
    password = PasswordField('密码', validators=[DataRequired()])
    submit = SubmitField('登录')
    
    class Meta:
        csrf = False

# 定义注册表单
class RegisterForm(FlaskForm):
    username = StringField('用户名', validators=[DataRequired(), Length(min=3, max=20)])
    password = PasswordField('密码', validators=[DataRequired(), Length(min=6)])
    confirm_password = PasswordField('确认密码', validators=[DataRequired(), EqualTo('password')])
    email = StringField('邮箱', validators=[DataRequired(), Email()])
    submit = SubmitField('提交')
    
    class Meta:
        csrf = False

# 定义用户信息编辑表单
class EditProfileForm(FlaskForm):
    username = StringField('用户名', validators=[DataRequired(), Length(min=3, max=20)])
    email = StringField('邮箱', validators=[DataRequired(), Email()])
    address = StringField('地址', validators=[Length(max=100)])
    submit = SubmitField('保存更改')
    
    class Meta:
        csrf = False

# 定义路由
@app.route('/')
def index():
    """首页"""
    return render_template('index.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    """登录页面"""
    # 检查用户是否已登录
    if session.get('user_id'):
        flash('您已经登录了！', 'info')
        return redirect(url_for('index'))
    
    form = LoginForm()
    if form.validate_on_submit():
        username = form.username.data
        password = form.password.data
        
        # 查询用户 - 使用name字段而不是username
        user = UserActual.query.filter_by(name=username).first()
        
        if user and user.password == password:  # 明文密码验证
            # 登录成功，设置session
            session['user_id'] = user.id
            session['username'] = user.name
            
            db.session.commit()
            
            flash(f'欢迎回来，{username}！', 'success')
            return redirect(url_for('index'))
        else:
            flash('用户名或密码错误！', 'danger')
    
    return render_template('login.html', form=form)

@app.route('/register', methods=['GET', 'POST'])
def register():
    """注册页面"""
    # 检查用户是否已登录
    if session.get('user_id'):
        flash('您已经登录了！', 'info')
        return redirect(url_for('index'))
    
    form = RegisterForm()
    if form.validate_on_submit():
        username = form.username.data
        password = form.password.data
        confirm_password = form.confirm_password.data
        
        # 检查密码是否匹配
        if password != confirm_password:
            flash('两次输入的密码不一致！', 'danger')
            return render_template('register.html', form=form)
        
        # 检查用户名是否已存在 - 使用name字段
        existing_user = UserActual.query.filter_by(name=username).first()
        if existing_user:
            flash('用户名已存在！', 'danger')
            return render_template('register.html', form=form)
        
        # 创建新用户 - 使用实际的数据库字段
        new_user = UserActual(
            name=username,  # 使用name字段而不是username
            password=password,  # 明文存储
            email=form.email.data,
            addr='',  # 默认空地址
            collect_id='',  # 默认空收藏ID
            seen_id=''  # 默认空浏览ID
        )
        
        db.session.add(new_user)
        db.session.commit()
        
        flash('注册成功！请登录。', 'success')
        return redirect(url_for('login'))
    
    return render_template('register.html', form=form)

@app.route('/logout')
def logout():
    """退出登录"""
    session.clear()
    flash('您已成功退出登录！', 'info')
    return redirect(url_for('index'))

@app.route('/user')
def user_profile():
    """用户资料页面"""
    # 检查用户是否已登录
    if not session.get('user_id'):
        flash('请先登录！', 'warning')
        return redirect(url_for('login'))
    
    # 获取用户信息 - 使用实际的模型
    user = UserActual.query.get(session['user_id'])
    
    # 创建编辑表单并预填充数据
    form = EditProfileForm()
    form.username.data = user.name
    form.email.data = user.email
    form.address.data = user.addr
    
    return render_template('user.html', 
                          user=user,
                          form=form,
                          registration_time='未知',  # 数据库中没有创建时间字段
                          last_login='未知')

@app.route('/user/edit', methods=['GET', 'POST'])
def edit_profile():
    """编辑用户信息页面"""
    # 检查用户是否已登录
    if not session.get('user_id'):
        flash('请先登录！', 'warning')
        return redirect(url_for('login'))
    
    # 获取当前用户信息
    user = UserActual.query.get(session['user_id'])
    form = EditProfileForm()
    
    # 如果是GET请求，预填充表单数据
    if request.method == 'GET':
        form.username.data = user.name
        form.email.data = user.email
        form.address.data = user.addr
    
    # 处理表单提交
    if form.validate_on_submit():
        new_username = form.username.data
        new_email = form.email.data
        new_address = form.address.data
        
        # 检查用户名是否已存在（排除当前用户）
        if new_username != user.name:
            existing_user = UserActual.query.filter_by(name=new_username).first()
            if existing_user and existing_user.id != user.id:
                flash('用户名已存在！', 'danger')
                return render_template('edit_profile.html', form=form, user=user)
        
        # 检查邮箱是否已存在（排除当前用户）
        if new_email != user.email:
            existing_email = UserActual.query.filter_by(email=new_email).first()
            if existing_email and existing_email.id != user.id:
                flash('邮箱已被使用！', 'danger')
                return render_template('edit_profile.html', form=form, user=user)
        
        try:
            # 更新用户信息
            user.name = new_username
            user.email = new_email
            user.addr = new_address
            
            db.session.commit()
            
            # 更新session中的用户名
            session['username'] = new_username
            
            flash('用户信息更新成功！', 'success')
            return redirect(url_for('user_profile'))
            
        except Exception as e:
            db.session.rollback()
            flash(f'更新失败：{str(e)}', 'danger')
            return render_template('edit_profile.html', form=form, user=user)
    
    return render_template('edit_profile.html', form=form, user=user)

# 健康检查路由
@app.route('/health')
def health_check():
    """健康检查端点"""
    try:
        # 测试数据库连接
        result = db.session.execute(text('SELECT 1')).fetchone()
        return {
            'status': 'healthy',
            'database': 'connected',
            'message': '应用运行正常'
        }
    except Exception as e:
        return {
            'status': 'unhealthy',
            'database': 'disconnected',
            'error': str(e)
        }, 500

if __name__ == '__main__':
    print("=== 启动干净的Flask应用 ===")
    print("应用URL: http://127.0.0.1:5000")
    print("健康检查: http://127.0.0.1:5000/health")
    print("登录页面: http://127.0.0.1:5000/login")
    print("注册页面: http://127.0.0.1:5000/register")
    print("\n按 Ctrl+C 停止应用")
    
    app.run(debug=True, host='127.0.0.1', port=5000)